﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.Util;
using Emgu.CV.UI;
using System.Windows.Forms;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using DSkin.Forms;
using TY.Utilities;

namespace TY_Hoist.WinApp.Code
{
    public class CVVideo
    {
        public static VideoCapture capture;
        public static List<Bitmap> imageList;
        public static event Action<string> dsplay;
        public static string videoPath;
        /// <summary>
        /// 打开视频
        /// </summary>
        /// <param name="pb"></param>
        public static int Open(string _videoPath)
        {
            try
            {
                videoPath = _videoPath;
                capture = new VideoCapture(videoPath);
                //this.capture.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.Exposure, -7);
                capture.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.Fps, 1000);
                //capture.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.PosFrames, 1000);
                int frameCount = Convert.ToInt32(capture.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameCount));
                //dsplay(frameCount.ToString());
                return frameCount;

                ////var avg = null;

                ////var frame = capture.QueryFrame();
                ////var resultFrame = new Mat(frame.Rows, frame.Cols, Emgu.CV.CvEnum.DepthType.Cv8U, 1);
                ////CvInvoke.CvtColor(frame, resultFrame, Emgu.CV.CvEnum.ColorConversion.Bgr2Gray);
                ////var resultFrame1 = new Mat(frame.Rows, frame.Cols, Emgu.CV.CvEnum.DepthType.Cv8U, 1);
                ////CvInvoke.GaussianBlur(resultFrame, resultFrame1, new Size(21, 21), 0);

                //Image<Bgr, byte> lastFrame = null;
                //Image<Bgr, byte> diffFrame = null;
                //var isFirstFrame = false;
                //using (Image<Bgr, byte> nextFrame = capture.QueryFrame().ToImage<Bgr, byte>())
                //{
                //    //pictureBox1.Image = nextFrame.ToBitmap();

                //    if (isFirstFrame)
                //    {
                //        //pictureBox2.Image = lastFrame.ToBitmap();

                //        diffFrame = nextFrame.AbsDiff(lastFrame);
                //        var moves = diffFrame.CountNonzero()[0];

                //        //pictureBox3.Image = diffFrame.ToBitmap();
                //        CvInvoke.PutText(nextFrame, moves.ToString(), new System.Drawing.Point(20, 20), Emgu.CV.CvEnum.FontFace.HersheyPlain, 1, new MCvScalar(255, 255, 0), 1);
                //        //setPictureBoxControlImage(pb, nextFrame.ToBitmap());
                //        //if (moves > 20)
                //        //    label1.Text = "moved!";
                //        //else
                //        //    label1.Text = "sleeps...";

                //    }

                //    lastFrame = nextFrame.Clone();
                //    isFirstFrame = true;
                //}
                //return 1000;



            }
            catch (Exception ex)
            {

                //dsplay(ex.ToString());
                return 0;
            }

            //imageList = new List<Bitmap>();
            //int readIndex = 0;
            //try
            //{
            //    while (true)
            //    {


            //        readIndex++;
            //        if (readIndex > frameCount)
            //        {

            //            break;
            //        }
            //        dsplay(readIndex.ToString());
            //        //获取图像帧
            //        Mat frame = capture.QueryFrame();


            //        //对帧添加时间
            //        //sw.Stop();
            //        //var fps = decimal.Round((decimal)(1000 / sw.Elapsed.TotalMilliseconds), 2);
            //        //CvInvoke.PutText(frame, fps.ToString(), new System.Drawing.Point(20, 20), Emgu.CV.CvEnum.FontFace.HersheyPlain, 1, new MCvScalar(255, 255, 0), 1);
            //        //if (frame != null)
            //        //{
            //        //    Image<Bgr, byte> imageFrame = frame.ToImage<Bgr, byte>();
            //        //    using (Bitmap im = imageFrame.Clone().ToBitmap())
            //        //    {
            //        //        //im.RotateFlip(RotateFlipType.Rotate180FlipNone);

            //        //        Bitmap tempBitmap = im.Clone(new RectangleF(0, 0, im.Width, im.Height), PixelFormat.Format24bppRgb);
            //        //        imageList.Add(new Bitmap(tempBitmap));
            //        //        //this.setPictureBoxControlImage(pb, new Bitmap(tempBitmap));
            //        //        tempBitmap.Dispose();

            //        //    }
            //        //    imageFrame.Dispose();
            //        //}
            //        //else
            //        //{

            //        //    break;
            //        //}
            //        //Thread.Sleep(10);

            //    }
            //}
            //catch (Exception ex)
            //{

            //    dsplay(ex.ToString());
            //}
        }
        //多线程设置PictureBox的图像
        public static void setPictureBoxControlImage(PictureBox control, int index)
        {
            capture.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.PosFrames, index - 1);
            Mat frame = capture.QueryFrame();
            if (frame != null)
            {
                Image<Bgr, byte> imageFrame = frame.ToImage<Bgr, byte>();
                using (Bitmap im = imageFrame.Clone().ToBitmap())
                {
                    //im.RotateFlip(RotateFlipType.Rotate180FlipNone);

                    Bitmap tempBitmap = im.Clone(new RectangleF(0, 0, im.Width, im.Height), PixelFormat.Format24bppRgb);
                    control.Invoke(new Action<PictureBox, Bitmap>((ct, v) => { ct.Image = v; }), new object[] { control, new Bitmap(tempBitmap) });

                    //this.setPictureBoxControlImage(pb, new Bitmap(tempBitmap));
                    tempBitmap.Dispose();

                }
                imageFrame.Dispose();
            }
        }
        //多线程设置PictureBox的图像
        public static void setPictureBoxControlImage(DSkin.Controls.DSkinPictureBox control, int index)
        {
            capture.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.PosFrames, index-1);
            Mat frame = capture.QueryFrame();
            if (frame != null)
            {
                Image<Bgr, byte> imageFrame = frame.ToImage<Bgr, byte>();
                using (Bitmap im = imageFrame.Clone().ToBitmap())
                {
                    //im.RotateFlip(RotateFlipType.Rotate180FlipNone);

                    Bitmap tempBitmap = im.Clone(new RectangleF(0, 0, im.Width, im.Height), PixelFormat.Format24bppRgb);
                    control.Invoke(new Action<DSkin.Controls.DSkinPictureBox, Bitmap>((ct, v) => { ct.Image = v; }), new object[] { control, new Bitmap(tempBitmap) });

                    //this.setPictureBoxControlImage(pb, new Bitmap(tempBitmap));
                    tempBitmap.Dispose();

                }
                imageFrame.Dispose();
            }
        }
        public static string CompletTest()
        {
            if (capture == null)
            {
                MessageBox.Show("当前状态不能完成试验！");
                return "0";
            }
            capture.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.PosFrames, StaticData.StartFrame);
            Mat frame = capture.QueryFrame();
            var filePath = System.Windows.Forms.Application.StartupPath + "/InterfaceServer/Resource/ExperimentTemp/" + StaticData.TestId;
            FileOpera.createPath(filePath);
            if (frame != null)
            {
                Image<Bgr, byte> imageFrame = frame.ToImage<Bgr, byte>();
                using (Bitmap im = imageFrame.Clone().ToBitmap())
                {

                    im.Save(filePath + "/startFrame.jpg", ImageFormat.Jpeg);

                }
                imageFrame.Dispose();
            }

            capture.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.PosFrames, StaticData.EndFrame);
            frame = capture.QueryFrame();
            if (frame != null)
            {
                Image<Bgr, byte> imageFrame = frame.ToImage<Bgr, byte>();
                using (Bitmap im = imageFrame.Clone().ToBitmap())
                {

                    im.Save(filePath + "/endFrame.jpg", ImageFormat.Jpeg);

                }
                imageFrame.Dispose();
            }

            FileOpera.copyFile(new System.IO.FileInfo(videoPath), filePath + "/CamVideo.avi");
            capture = null;
            return "1";
        }
    }
}
